package com.poetry.service.impl;

import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetry.constant.RedisConstant;
import com.poetry.domain.dto.PoemDoc;
import com.poetry.domain.po.Poem;
import com.poetry.domain.po.Search;
import com.poetry.exception.R;
import com.poetry.exception.SearchResult;
import com.poetry.mapper.SearchMapper;
import com.poetry.service.ISearchService;
import com.poetry.util.ESUtil;
import com.poetry.util.UserContext;
import jakarta.annotation.Resource;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.UncategorizedElasticsearchException;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Search>
        implements ISearchService {

    @Resource
    private ElasticsearchOperations elasticsearchOperations;
    @Resource
    private ElasticsearchClient elasticsearchClient;
    @Resource
    private ESUtil esUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    public R<SearchResult<PoemDoc>> searchPoems(String query, String type, String dynasty, String author, int page, int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            NativeQuery nativeQuery = esUtil.buildSearchQuery(query, type, dynasty, author, pageable);

            SearchHits<PoemDoc> searchHits = elasticsearchOperations.search(nativeQuery, PoemDoc.class);

            List<PoemDoc> poems = esUtil.processSearchHits(searchHits);
            PageImpl<PoemDoc> result = new PageImpl<>(poems, pageable, searchHits.getTotalHits());
            addHistory(query);
            return R.success("搜索成功", SearchResult.fromPage(result));
        } catch (UncategorizedElasticsearchException e) {
            return R.error("搜索失败：" + e);
        } catch (Exception e) {
            return R.error("系统错误：" + e.getMessage());
        }
    }

    public R<List<String>> getSuggestions(String prefix, int size) {
        if (prefix == null || prefix.trim().isEmpty()) {
            return R.success("自动补全成功", Collections.emptyList());
        }

        try {
            // 构建多字段自动补全查询
            SearchResponse<PoemDoc> response = elasticsearchClient.search(s -> {
                s.index("poems")
                        .source(src -> src.fetch(false)).suggest(sb -> {
                            // 标题建议
                            sb.suggesters("title_suggest", sug -> sug
                                    .prefix(prefix)
                                    .completion(c -> c
                                            .field("suggest_title")
                                            .skipDuplicates(true)
                                            .size(size / 3)
                                    ));
                            // 作者建议
                            sb.suggesters("author_suggest", sug -> sug
                                    .prefix(prefix)
                                    .completion(c -> c
                                            .field("suggest_author")
                                            .skipDuplicates(true)
                                            .size(size / 3)
                                    ));
                            // 内容建议
                            sb.suggesters("content_suggest", sug -> sug
                                    .prefix(prefix)
                                    .completion(c -> c
                                            .field("suggest_content")
                                            .skipDuplicates(true)
                                            .size(size)
                                    ));
                            return sb;
                        });
                s.size(0);
                return s;
            }, PoemDoc.class);

            // 提取并合并建议结果
            return R.success("自动补全成功", esUtil.extractAndMergeSuggestions(response, prefix));
        } catch (IOException e) {
            // 错误处理
            log.error("获取自动补全建议失败: " + e.getMessage(), e);
            return R.success("自动补全成功", Collections.emptyList());
        }
    }

    @Override
    @Transactional
    public R<String> addHistory(String content) {
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return R.error("用户未登录");
        }
        String listKey = RedisConstant.SEARCH_HISTORY_KEY + userId.toString();
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(setKey, content);
        Search search = new Search();
        search.setContent(content);
        search.setUserId(userId);
        search.setViewedAt(LocalDateTime.now());
        if (Boolean.TRUE.equals(isMember)) {
            // 浏览记录已存在则更新浏览时间
            this.update(
                    new LambdaUpdateWrapper<Search>()
                            .eq(Search::getUserId, userId)
                            .eq(Search::getContent, content)
                            .set(Search::getViewedAt, LocalDateTime.now()));
            removeRedisFromList(listKey, content);
        } else {
            this.save(search);
            stringRedisTemplate.opsForSet().add(setKey, content);
        }
        stringRedisTemplate.opsForList().leftPush(listKey, JSONUtil.toJsonStr(search));
        stringRedisTemplate.opsForList().trim(listKey, 0, RedisConstant.SEARCH_MAX_SIZE - 1);
        stringRedisTemplate.expire(listKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
        stringRedisTemplate.expire(setKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
        return R.success(null, "搜索记录添加成功");
    }

    private void removeRedisFromList(String key, String content) {
        List<String> value = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (value == null || value.isEmpty()) return;
        List<Search> list = value.stream().map(s -> JSONUtil.toBean(s, Search.class)).toList();
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            Search item = list.get(i);
            if (item.getContent().equals(content)) {
                index = i;
                break;
            }
        }
        // 删除找到的元素
        if (index >= 0) {
            // 设置占位符并删除
            stringRedisTemplate.opsForList().set(key, index, "TO_DELETE");
            stringRedisTemplate.opsForList().remove(key, 0, "TO_DELETE");
        }
    }

    @Override
    public R<List<Search>> queryHistory(Integer limit) {
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return R.error("用户未登录");
        }
        String listKey = RedisConstant.SEARCH_HISTORY_KEY + userId.toString();
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        List<String> list = stringRedisTemplate.opsForList().range(listKey, 0, limit - 1);
        if (list != null && !list.isEmpty()) {
            return R.success("查询历史记录成功", list.stream()
                    .map(s -> JSONUtil.toBean(s, Search.class)).toList());
        }
        List<Search> historyList = baseMapper.selectHistory(userId, limit);
        if (historyList != null && !historyList.isEmpty()) {
            stringRedisTemplate.opsForList().leftPushAll(listKey, JSONUtil.toJsonStr(historyList));
            stringRedisTemplate.opsForList().trim(listKey, 0, RedisConstant.HISTORY_MAX_SIZE - 1);
            Set<String> contents = historyList.stream().map(Search::getContent).collect(Collectors.toSet());
            if (!contents.isEmpty()) {
                stringRedisTemplate.opsForSet().add(setKey, contents.toString());
            }
            stringRedisTemplate.expire(listKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
            stringRedisTemplate.expire(setKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
        }
        return R.success("查询浏览记录成功", historyList);
    }

    @Override
    @Transactional
    public R<String> clearHistory() {
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return R.error("用户未登录");
        }
        baseMapper.delete(new LambdaQueryWrapper<Search>().eq(Search::getUserId, userId));
        String listKey = RedisConstant.SEARCH_HISTORY_KEY + userId;
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        stringRedisTemplate.delete(listKey);
        stringRedisTemplate.delete(setKey);
        return R.success(null, "清空浏览记录成功");
    }

    @Override
    public void addOrUpdatePoem(Poem poem) {
        PoemDoc doc = convertToIndex(poem);
        elasticsearchOperations.save(doc);
    }

    @Override
    public void deletePoem(List<Integer> poemId) {
        for (Integer id : poemId) {
            elasticsearchOperations.delete(id);
        }
    }

    private PoemDoc convertToIndex(Poem poem) {
        PoemDoc doc = new PoemDoc();
        doc.setId(poem.getId());
        doc.setTitle(poem.getTitle());
        doc.setDynasty(poem.getDynasty());
        doc.setAuthor(poem.getAuthor());
        doc.setContent(poem.getContent());
        doc.populateSuggestions();
        return doc;
    }
}
